package bean;

import bean.Being.Dog;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试Spring的EL
 */
public class SpELTest {
    public static void main(String[] args) {
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'HelloWorld'");
        System.out.println(exp.getValue());

        exp = parser.parseExpression("'HelloWorld'.bytes");
        System.out.println(exp.getValue());

        exp = parser.parseExpression("new String('HelloWorld').toUpperCase()");
        System.out.println(exp.getValue(String.class));

        //添加root对象
        exp = parser.parseExpression("msg");
        Dog dog = new Dog();
        dog.setMsg("dog");
        System.out.println(exp.getValue(dog,String.class));

        exp = parser.parseExpression("msg == 'dog'");
        System.out.println(exp.getValue(dog));

        //使用上下文
        StandardEvaluationContext ctx = new StandardEvaluationContext();
        ctx.setRootObject(dog);
        System.out.println(exp.getValue(ctx));

        List<Boolean> list = new ArrayList<>();
        list.add(true);
        EvaluationContext ctx2 = new StandardEvaluationContext();
        ctx2.setVariable("list",list);
        System.out.println(parser.parseExpression("#list[0]").getValue(ctx2));
        parser.parseExpression("#list[0]").setValue(ctx2,"false");
        System.out.println(parser.parseExpression("#list[0]").getValue(ctx2));
    }
}
